package inspur.dao;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import inspur.common.ConnectionUtils;
import inspur.entity.CookieTokenObject;
import inspur.entity.User;

import javax.servlet.http.HttpServletRequest;
import java.sql.*;

public class UserDao {
	Connection conn=null;
	PreparedStatement pstm=null;
	ResultSet rs=null;
	/**
		用户注册，输入User，并将其添加到数据库中
		参数User user
		返回：返回 int flag
					if  flag=0//注册失败
						flag=2//注册成功


	 */
	public int reg(User user){
		//得到数据库对象
		conn= ConnectionUtils.getConnection();
		int flag=0;//注册失败
		try {
			//发送sql文
			String sql="insert  into user(userid,username,password,Identity) VALUES(?,?,?,'au')";
			pstm= conn.prepareStatement(sql);
			pstm.setString(1,user.getId());
			pstm.setString(2,user.getUsername());
			pstm.setString(3,user.getPassword());
			//rs= pstm.executeQuery();
            int num=pstm.executeUpdate();
			//int num=pstm.executeUpdate();
			//处理结果集
			if (num==1){
				flag=2;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}finally{

			//释放资源
			ConnectionUtils.close(rs, pstm, conn);
		}
		return flag;

	}
	/**
		用户登陆，输入一个user对象，判断是否为数据库的中user
		参数：User user
		返回 int flag
					if  flag=0//用户不存在
						flag=2//用户名和密码都正确
						flag=1//密码错误
	 */

	public int login(User user){

		//得到数据库对象
		conn= ConnectionUtils.getConnection();

		int flag=0;//用户名不存在
		try {
			//发送sql文


			String sql="INSERT  INTO ";
			pstm= conn.prepareStatement(sql);
			pstm.setString(1, user.getId()
			);
			rs= pstm.executeQuery();

			//处理结果集
			while(rs.next()){
				String temp=rs.getString("password");
				if(temp.equals(user.getPassword())){
					//用户名和密码都正确
					flag=2;

				}else{
					//密码不正确
					flag=1;
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}finally{

			//释放资源
			ConnectionUtils.close(rs, pstm, conn);
		}
		return flag;

	}
	/**
		获取符合指定条件的一组User
	 */
	public static User[] getSomeUsers(){
		return null;
	}
	/**
		获取符合指定条件的一个User对象
	 */
	public static User getUserByUserId(String value){
        Connection conn=null;
        PreparedStatement pstm=null;
        ResultSet rs=null;
	    conn=ConnectionUtils.getConnection();
	    User user=new User();//User对象
        try {
            //发送sql
            String sql="select * from user where userid=?";
            pstm=conn.prepareStatement(sql);
            pstm.setString(1,value);
            rs=pstm.executeQuery();
            System.out.println(rs);
            while (rs.next()){
                user.setId(rs.getString("userid"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setGroup(rs.getString("mygroup"));
                user.setOrg(rs.getString("organization"));
                user.setIdentity(rs.getString("Identity"));
                user.setTell(rs.getString("tell"));
                user.setQq(rs.getString("qq"));
                user.setVx(rs.getString("vx"));
                user.setProvince(rs.getString("province"));
                user.setCity(rs.getString("city"));
                user.setArea(rs.getString("area"));
                user.setAddress(rs.getString("address"));
                user.setEmail(rs.getString("email"));
                user.setAge(rs.getString("age"));
                user.setIntroduction(rs.getString("Introduction"));
                user.setTemppass(rs.getString("temppass"));
                return user;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
	}
	/*
		删除符合指定条件的一个User对象
	 */
	public static int delectUser(String userid){
        Connection conn=null;
        PreparedStatement pstm=null;
        ResultSet rs=null;
        //得到数据库对象
        conn= ConnectionUtils.getConnection();
        int flag=0;//注册失败
        try {
            //发送sql文
            String sql="DELETE  FROM user WHERE userid=?";
            pstm= conn.prepareStatement(sql);
            pstm.setString(1,userid);
            //rs= pstm.executeQuery();
            int num=pstm.executeUpdate();
            //int num=pstm.executeUpdate();
            //处理结果集
            if (num==1){
                flag=2;
            }
        } catch (MySQLIntegrityConstraintViolationException e){
            flag=3;
        }catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }finally{

            //释放资源
            ConnectionUtils.close(rs, pstm, conn);
        }
        return flag;
	}
	/*
	删除符合制定条件的一组User
	 */
	public int delectSomeUser(String userid){
        Connection conn=null;
        PreparedStatement pstm=null;
        ResultSet rs=null;
        //得到数据库对象
        conn= ConnectionUtils.getConnection();
        int flag=0;//注册失败
        try {
            //发送sql文
            String sql="DELETE  FROM user WHERE userid=?";
            pstm= conn.prepareStatement(sql);
            pstm.setString(1,userid);
            //rs= pstm.executeQuery();
            int num=pstm.executeUpdate();
            //int num=pstm.executeUpdate();
            //处理结果集
            if (num==1){
                flag=2;
            }
        } catch (MySQLIntegrityConstraintViolationException e){
            flag=3;
        }catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }finally{

            //释放资源
            ConnectionUtils.close(rs, pstm, conn);
        }
        return flag;
	}
	/**
	修改某个User对象的信息

	 */
	public static int editUser(String userid,User _user){
        Connection conn=null;
        PreparedStatement pstm=null;
        ResultSet rs=null;
        //得到数据库对象
        conn= ConnectionUtils.getConnection();
        int flag=0;//注册失败
        try {
            //发送sql文
              String sql="UPDATE user SET userid=?,username=?,password=?,mygroup=?,organization=?,Identity=?,tell=?,qq=?,vx=?,province=?,city=?,area=?,address=?,email=?,age=?,Introduction=?,temppass=? WHERE userid=?";
            pstm= conn.prepareStatement(sql);
            pstm.setString(1,_user.getId());
            pstm.setString(2,_user.getUsername());
            pstm.setString(3,_user.getPassword());
            pstm.setString(4,_user.getGroup());
            pstm.setString(5,_user.getOrg());
            pstm.setString(6,_user.getIdentity());
            pstm.setString(7,_user.getTell());
            pstm.setString(8,_user.getQq());
            pstm.setString(9,_user.getVx());
            pstm.setString(10,_user.getProvince());
            pstm.setString(11,_user.getCity());
            pstm.setString(12,_user.getArea());
            pstm.setString(13,_user.getAddress());
            pstm.setString(14,_user.getEmail());
            pstm.setString(15,_user.getAge());
            pstm.setString(16,_user.getIntroduction());
            pstm.setString(17,_user.getTemppass());
            pstm.setString(18,userid);
            //rs= pstm.executeQuery();
            int num=pstm.executeUpdate();
            //int num=pstm.executeUpdate();
            //处理结果集
            if (num==1){
                flag=2;
            }
        } catch (MySQLIntegrityConstraintViolationException e){
            flag=3;
        }catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }finally{
            //释放资源
            ConnectionUtils.close(rs, pstm, conn);
        }
        return flag;


	}

    /**判断登陆状态
     *@param request
     * @return  boolean
     */
	public static User isLogin(HttpServletRequest request){
        CookieTokenObject browerCTO= CookieDao.CreatCookieTokenObject(request);//从cookie中获取令牌对象
			if(browerCTO!=null){
				User user= UserDao.getUserByUserId(browerCTO.getUserid().getValue().toString());//从数据库中获取user对象
				 if (user!=null){
				//判断登陆状态
				if (CookieDao.isTrueToken(browerCTO,user.getPassword(),request)){
					return  user;
				}else{
					return null;
				}
			}else {
				return null;
			}
		}else{
				return null;
			}


    }

    public  static boolean isAdmin(String it){
	    boolean ad=false;//默认不具有访问身份
        if (it.equals("admin")){
            ad=true;
        }

	    return ad;
    }
	
}
